package com.aes;

import cn.hutool.core.util.RandomUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class AESEncryptHandler extends BaseTypeHandler {



    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {

            String preStr = RandomUtil.randomChar()+"";
            String str = "$#"+preStr+AES.encrypt((String)parameter);
            ps.setString(i, str);


    }
    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String columnValue = rs.getString(columnName);
        if (columnValue!=null && columnValue.startsWith("$#") && columnValue.length()>=3)
        {
            return AES.decrypt(columnValue.substring(3));
        }
        return columnValue;
    }
    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String columnValue = rs.getString(columnIndex);
        if (columnValue!=null && columnValue.startsWith("$#") && columnValue.length()>=3)
        {
            return AES.decrypt(columnValue.substring(3));
        }
        return columnValue;
    }
    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        String columnValue = cs.getString(columnIndex);
        if (columnValue!=null && columnValue.startsWith("$#") && columnValue.length()>=3)
        {
            return AES.decrypt(columnValue.substring(3));
        }
        return columnValue;
    }
}